package cn.xzqwjw.taskmanager.security.handler;

import cn.xzqwjw.taskmanager.common.customEnum.ResponseCodeEnum;
import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import cn.xzqwjw.taskmanager.utils.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义验证jwt失败时的错误输出格式，这里是输出成json
 *
 * @author rush
 */
public class AuthJwtFailedHandler implements AuthenticationFailureHandler {

  @Override
  public void onAuthenticationFailure(HttpServletRequest request,
                                      HttpServletResponse response,
                                      AuthenticationException exception) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    String code = ResponseCodeEnum.BAD_REQUEST.getStatusCode();
    String message = exception.getMessage();
    // 验证失败，说明请求带的jwt无效，因此这里的响应返回jwt是个空值
    ResponseUtil.writeJsonJwt(response, "", ResponseVo.error(code, message));
  }

}